package fr.esiag.isidis.epp.csv;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import fr.esiag.isidis.epp.generatedClasses.CourbeDeCharge;
import fr.esiag.isidis.epp.generatedClasses.PointCdc;
import fr.esiag.isidis.epp.generatedClasses.PointConso;
import fr.esiag.isidis.epp.generatedClasses.Query;
import fr.esiag.isidis.epp.generatedClasses.QueryExportCdc;
import fr.esiag.isidis.epp.search.PointCdcService;
import fr.esiag.isidis.epp.service.JaxbConverter;
import fr.esiag.isidis.epp.util.Utils;


public class GenerateCsv {
	FileWriter file;
	
	private static Logger logger = Logger.getLogger(GenerateCsv.class);
	/**
	 * 
	 * @param name
	 * @param type (cdc = 1; temperature = 2 ...)
	 */
	public GenerateCsv(String name, int type) {
		try {
			this.file = new FileWriter(name+".csv");
			if(type == 1) {
				file.write("Idsite;Date;Cdc \n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void write(String val) {
		try {
			file.write(val + (";"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void writeLinecdc(String idsite, String date, String cdc) {
		try {
			file.write(idsite +";"+ date +";"+ cdc + "; \n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doCdcCsv(PointConso pc) {
		String idString = pc.getIDSite();
		CourbeDeCharge cdc = pc.getCourbeDeCharge();
		
		for(PointCdc p : cdc.getPointCdc() ) {
			int dateI = p.getDateConso();
			int heure = p.getHeureConso();
			String puissance = String.valueOf(p.getPuissanceSoutire());
			String date = Utils.makedate(dateI,heure);
			writeLinecdc(idString, date, puissance);
		}
	}
	
	public void close() {
		try {
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext("classpath:/epp-context.xml");
		JaxbConverter converter = context.getBean(JaxbConverter.class);
		// unmashal xml file to java object
		QueryExportCdc pp = converter.unmarshalerPointConso("src/main/resources/query.xml");
		List<Query> list=pp.getQuery();
		PointCdcService pt = context.getBean(PointCdcService.class);
		PointConso pc =  pt.traiteQuery(pp);
		GenerateCsv csv = new GenerateCsv("test",1);
		csv.doCdcCsv(pc);
		csv.close();
	}
}
